package com.imooc.bilibili.service.impl;

import com.imooc.bilibili.constant.AuthRoleConstant;
import com.imooc.bilibili.entity.RoleElementRelation;
import com.imooc.bilibili.entity.RoleInfo;
import com.imooc.bilibili.entity.RoleMenuRelation;
import com.imooc.bilibili.entity.UserRoleRelation;
import com.imooc.bilibili.service.AuthRoleService;
import com.imooc.bilibili.service.UserAuthService;
import com.imooc.bilibili.service.UserRoleService;
import com.imooc.bilibili.vo.UserAuthorities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

@Service("userAuthService")
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private AuthRoleService authRoleService;

    @Override
    public UserAuthorities getUserAuthoritiesService(Long userId) {
        //根据userId查询角色信息
        List<UserRoleRelation> userRoleList = userRoleService.getUserRoleByUserId(userId);
        List<Long> roleIdList = userRoleList.stream().map(UserRoleRelation :: getRoleId).distinct().collect(Collectors.toList());

        //根据roleId查询权限
        List<RoleElementRelation> roleElementList = authRoleService.getRoleElementByRoleIds(roleIdList);
        //根据roleId查询菜单权限
        List<RoleMenuRelation> roleMenuList = authRoleService.getRoleMenuByRoleIds(roleIdList);

        //封装权限信息
        UserAuthorities authorities = new UserAuthorities();
        authorities.setElementInfos(roleElementList);
        authorities.setMenuInfos(roleMenuList);
        return authorities;
    }

    @Override
    public void insertUserDefaultRoleService(Long userId) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        UserRoleRelation relation = new UserRoleRelation();

        RoleInfo roleInfo = authRoleService.queryRoleByRoleCode(AuthRoleConstant.ROLE_CODE_LV0);
        relation.setUserId(userId);
        relation.setRoleId(relation.getRoleId());
        relation.setEnableState(0);
        relation.setDeleteState(0);
        relation.setCreateTime(timestamp);
        relation.setUpdateTime(timestamp);
        userRoleService.insertUserRoleRelationServicee(relation);
    }
}
